import { _window } from '@/global.ts'
import BaseApi from '../utils/base.api.ts'
import { typeCheck } from '@/utils/types.ts'
import { getIconsByName, getIconNames, searchIcon } from '@/api/interface/icon.ts'

export type iconPrefixType = 'proicons' | 'hugeicons' | 'typcn' | 'weui'
export const iconPrefix = ['proicons', 'hugeicons', 'typcn', 'weui']
class IconData extends BaseApi {
  nameMap = new Map<iconPrefixType, string[]>()
  specificData = new Map<string, string>()
  currentType: iconPrefixType | null = null // 当前选中的icon类型
  total: number = 0 // 当前选中类型icon的数量

  // 获取当前type下的icon数和name
  async getIconNames(type: iconPrefixType) {
    try {
      const res: any = await getIconNames(type)
      if (res.uncategorized && typeCheck(res.uncategorized, 'array')) {
        this.nameMap.set(type, res.uncategorized)
        this.total = res.uncategorized.length
        this.currentType = type
        return true
      }
      return false
    } catch (error) {
      _window._log.error(`请求失败: ${error}`) // 直接捕获错误
      return false
    }
  }

  async getIconsByPage(pageIndex: number, pageSize: number) {
    if (!this.currentType) throw new Error('请先获取对应type的icon-name')
    if (pageIndex <= 0) {
      _window._log.error(`输入的pageIndex不合法`)
      return []
    }
    const maxPage = this.total / pageSize + (this.total / pageSize > 0 ? 1 : 0)
    if (pageIndex > maxPage) {
      _window._log.error(`请求的数量大于icon的数量${this.total / pageSize}`)
      return []
    }
    const startIndex = (pageIndex - 1) * pageSize
    const endIndex = pageIndex * pageSize
    const iconNames = this.nameMap.get(this.currentType)
    if (iconNames) {
      let names = []
      for (let i = startIndex; i < endIndex && i < this.total; ++i) {
        names.push(iconNames[i])
      }
      const res: any = await getIconsByName(this.currentType, names.join(','))
      const icons: { icon: string; name: string }[] = []
      if (res.icons) {
        const keys = Object.keys(res.icons)
        for (let j = 0; j < keys.length; ++j) {
          const key = keys[j]
          const icon = res.icons[key!]
          icons.push({
            name: `${this.currentType}:${key}`,
            icon: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">${icon.body}</svg>`,
          })
        }
      }
      return icons
    }
    return []
  }

  async searchIcons(key: string) {
    try {
      if (!key || key.trim().length === 0) return false
      const res: any = await searchIcon(this.currentType!, key)
      if (res.icons && typeCheck(res.icons, 'array')) {
        const icons = []
        for (let i = 0; i < res.icons.length; ++i) {
          const iconsName = res.icons[i].split(':')
          if (iconsName && iconsName.length === 2) {
            icons.push(iconsName[1])
          }
        }
        this.nameMap.set(this.currentType!, icons)
        this.total = icons.length
        return true
      }
      return false
    } catch (error) {
      _window._log.error(`请求失败: ${error}`)
      return false
    }
  }

  override clear() {
    this.nameMap.clear()
    this.specificData.clear()
  }
}

export const iconData = new IconData()
